package com.yicong.ants.ui.me.address;

import android.graphics.Color;
import android.util.Pair;
import android.view.View;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.cchao.simplelib.core.JsonHelper;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.cchao.simplelib.util.ThreadHelper;
import com.google.gson.Gson;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.JsonBean;
import com.yicong.ants.bean.me.AddressItemBean;
import com.yicong.ants.databinding.AddressEditActivityBinding;
import com.yicong.ants.manager.UiAssistant;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.utils.JsonUtils;
import com.yicong.ants.utils.KeyBoardUtils;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONArray;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 新建或修改地址
 *
 * @author cchao
 * @since 2019-12-26
 */
public class AddEditAddressActivity extends BaseTitleBarActivity<AddressEditActivityBinding> implements View.OnClickListener {
    AddressItemBean mBean;

    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();

    @Override
    protected int getLayout() {
        return R.layout.address_edit_activity;
    }

    @Override
    protected void initEventAndData() {
        mBean = JsonHelper.toObject(getIntent().getStringExtra(Constants.Extra.JSON), AddressItemBean.class);
        setTitleText("编辑地址");
        mDataBind.setClick(this);
        UiHelper.setVisibleElseGone(mDataBind.apply, mBean != null);

        if (mBean != null) {
            mDataBind.setBean(mBean);
        } else {
            mBean = new AddressItemBean();
        }

        addTitleMenuItem(UiAssistant.getAtyMenuText(mContext, "保存"), view -> {
            //
            onSave();
        });
        onLoadData();
    }

    private void onSave() {
        mBean.setName(mDataBind.name.getValue());
        mBean.setMobile(mDataBind.mobile.getValue());
        mBean.setDetail(mDataBind.detail.getValue());
        mBean.setIs_default(mDataBind.radio.isChecked() ? 1 : 0);
        showProgress();
        addSubscribe(RetrofitHelper.getApis().updateAddress(JsonHelper.toMap(JsonHelper.toJson(mBean), String.class))
            .compose(RxHelper.toMain())
            .subscribe(respBean -> {
                hideProgress();
                showToast(respBean.getMsg());
                if (respBean.isCodeFail()) {
                    return;
                }
                finish();
                RxBus.get().postEvent(Constants.Event.update_address);
            }, RxHelper.getHideProgressConsumer(this)));
    }

    @Override
    protected void onLoadData() {
        ThreadHelper.execute(new Runnable() {
            @Override
            public void run() {
                initJsonData();
            }
        });
    }

    private void showPickerView() {
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
            String tx;
            if ("其他".equals(options3Items.get(options1).get(options2).get(options3))) {
                tx = StringUtils.trim(options1Items.get(options1).getPickerViewText()) + "-" +
                    StringUtils.trim(options2Items.get(options1).get(options2));
                mBean.setProvince(options1Items.get(options1).getPickerViewText());
                mBean.setCountry(options2Items.get(options1).get(options2));
            } else {
                //返回的分别是三个级别的选中位置
                tx = StringUtils.trim(options1Items.get(options1).getPickerViewText()) + "-" +
                    StringUtils.trim(options2Items.get(options1).get(options2)) + "-" +
                    StringUtils.trim(options3Items.get(options1).get(options2).get(options3));

                mBean.setProvince(options1Items.get(options1).getPickerViewText());
                mBean.setCity(options2Items.get(options1).get(options2));
                mBean.setCountry(options3Items.get(options1).get(options2).get(options3));
            }
            mDataBind.area.setValue(tx);

        }).setTitleText(getResources().getString(R.string.city_selection))
            .setDividerColor(Color.BLACK)
            .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
            .setContentTextSize(20)
            .build();

        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    private void initJsonData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = JsonUtils.getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                    || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            // 添加城市数据
            options2Items.add(CityList);

            // 添加地区数据
            options3Items.add(Province_AreaList);
        }
    }

    public ArrayList<JsonBean> parseData(String result) {
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.apply:
                UiHelper.showCancelDialog(mContext, "是否确定删除？", Pair.create("确定", (dialogInterface, i) -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("id", mBean.getId());
                    showProgress();
                    addSubscribe(RetrofitHelper.getApis().deleteAddress(map)
                        .compose(RxHelper.toMain())
                        .subscribe(respBean -> {
                            hideProgress();
                            showToast(respBean.getMsg());
                            if (respBean.isCodeFail()) {
                                return;
                            }
                            finish();
                            RxBus.get().postEvent(Constants.Event.update_address);
                        }, RxHelper.getHideProgressConsumer(AddEditAddressActivity.this)));
                }), Pair.create("取消", null));
                break;
            case R.id.area:
                KeyBoardUtils.closeKeybord(this);
                showPickerView();
                break;
        }
    }
}
